<template>
  <BasicDrawer v-bind="$attrs" @register="registerDrawer" :showFooter="true" :title="getTitle" width="100%"
    :show-ok-btn="false" @cancel="cancelFn">
    <!--    @cancel="cancelFn"-->
    <div style="height: 100%">
      <approverStatusIcon :status="dataList.status"></approverStatusIcon>


      <div style="width: 100%; height: 450px">
        <!-- v-on="gridEvents" overflow: hidden -->
        <div>
          审批单据编号: <span>{{ approveNo }}</span>
        </div>
        <!-- <watermarkContainer :text="statusObj.val" :color="statusObj.color"> -->
        <div style="padding-top: 8px;font-weight: bold" :style="{ color: statusObj.color }">{{ statusObj.val }}
        </div>
        <div style="padding-top: 8px;">
          {{ dataList.title }}
        </div>
        <div style="padding-top: 8px;font-weight: bold;">合计:</div>

        <div v-if="dataList.fileDataJson">

          <div style="display: flex; align-items: center;">
            <div class="count-i" v-for="(item, index) in headTitles">
              {{ item }}
            </div>
          </div>
          <div v-for="(item, index) in headList" style="display: flex; align-items: center;">
            <div class="count-i">{{ item.姓名 }}</div>
            <div class="count-i">{{ item.回款总额 }}</div>
            <div class="count-i">{{ item.提成比例 * 100 }}%</div>
            <div class="count-i count-i-p">{{ item.提成金额 }}元 </div>

          </div>

          <div style="margin-top: 8px;">
            附件: <a v-if="dataList.fileUrl" :href="dataList.fileUrl" target="_blank">{{ dataList.fileUrl }}</a>
          </div>

        </div>

        <div v-if="countApproverList.length > 0">

          <div v-for="(item, index) in countApproverList" style="display: flex; align-items: center;">
            <div class="count-i">{{ getUserName(item) }}
              <span>{{ item.userType == 'manage_user' ? '(经理)' : '' }}</span>
            </div>
            <div class="count-i count-i-p">{{ item.userPrice }}元 </div>
            <div style="margin-left: 5px;" v-if="item.note">

              ({{ item.note }})
            </div>

          </div>
        </div>
        <div v-if="dataList.stateName">该单据 <span style="color: red;">{{ dataList.stateName }}</span> 请重新发起审批</div>

        <!-- </watermarkContainer> -->

        <vxe-grid ref="tableRef" v-bind="gridOptions">
          <template #toolbar_buttons>
            单据明细 <Button style="margin-left: 8px;" size="small" type="primary" v-if="!dataList.fileUrl"
              @click="openAllFaPiaoFn">查看全部发票明细(不包含已排除)</Button>
          </template>
          <template #footer_totalAllPrice>
            <span>{{ totalObj.totalAllPrice }}{{ totalObj.totalAllPrice ? '元' : '' }}</span>
          </template>
          <template #footer_orderCommissionPrice>
            <span style="color: red;">{{ totalObj.orderCommissionPrice }}{{ totalObj.totalAllPrice ? '元' : ''
            }}</span>
          </template>
          <template #footer_receiverUserPrice>
            <span style="color: red;">{{ totalObj.receiverUserPrice }}{{ totalObj.receiverUserPrice ? '元' : ''
            }}</span>
          </template>
          <template #footer_merchandiserUserPrice>
            <span style="color: red;">{{ totalObj.merchandiserUserPrice }}{{ totalObj.merchandiserUserPrice ? '元' : ''
            }}</span>
          </template>
          <template #footer_manageUserPrice>
            <span style="color: red;">{{ totalObj.manageUserPrice }}{{ totalObj.manageUserPrice ? '元' : '' }}</span>
          </template>
          <template #footer_xiangMuGroupPrice>
            <span style="color: red;">{{ totalObj.xiangMuGroupPrice }}{{ totalObj.xiangMuGroupPrice ? '元' : ''
            }}</span>
          </template>
          <template #footer_jiJingPrice>
            <span style="color: red;">{{ totalObj.jiJingPrice }}{{ totalObj.jiJingPrice ? '元' : '' }}</span>
          </template>
        </vxe-grid>
        <approverLogView :approveNo="approveNo" :api="ywApprovalLogView" ref="approverLogViewRef" @success="reloadFn"
          :approvalLogId="approvalLogId"></approverLogView>

      </div>

      <FaPiaoItemModal @register="skrq[0]"></FaPiaoItemModal>
      <yuShouDetailModal @register="yushouModal[0]"></yuShouDetailModal>
    </div>

    <template #footer>
      <Button @click="cancelFn">关闭</Button>
      <approverLogButton :approveNo="approveNo" ref="approverLogButtonRef" :passApi="ywApprovalPass" :list="affrimLogList"
        :back-api="ywApprovalBack" @success="reloadFn"></approverLogButton>

    </template>
  </BasicDrawer>
</template>
<script lang="ts" setup>
import { ref, computed, unref, h, toRaw, reactive } from 'vue';
import approverLogView from '@/views/components/approverLogView/list.vue';
import approverLogButton from '@/views/components/approverLogButton/approverLogButton.vue'
import watermarkContainer from '@/views/components/watermarkContainer.vue';
import approverStatusIcon from '@/views/components/approverStatusIcon/index.vue';

import {
  BasicTableProps,
  VxeBasicTable,
  VxeGridInstance,
  VxeGridListeners, VxeGridPropTypes,
  VxeTableDefines,
} from '@/components/VxeTable';
import {
  paseTags2
} from './role.data';
import {
  k3Columns
} from '../ywMoneyList/role.data';
import util from '@/utils/util';

import {
  checkboxCountFn2
} from '../../dknMoneyList/role.data';
const statusObj = ref({ val: "", color: "" })


import { BasicModal, useModal, useModalInner } from '@/components/Modal';
import { Form, Button, Input, InputNumber, DatePicker, Select } from 'ant-design-vue';
import { BasicDrawer, useDrawerInner } from '@/components/Drawer';
import { ywApprovalLogView, ywApprovalShow, ywApprovalPass, ywApprovalBack, countApproverNoTotal, ywApprovalDetail, ywApprovalDetailByApproveNo } from '@/api/sys/approval';
import { BasicListResult, BasicDataResult } from '@/api/model/baseModel';

import { BasicTree, TreeItem } from '@/components/Tree';
import { moneyAffrimLogList } from '@/api/heng/ywManage';
import { useMessage } from "@/hooks/web/useMessage";
import FaPiaoItemModal from "@/views/heng/yw2/ywMoneyList/FaPiaoItemModal.vue";
import yuShouDetailModal from '@/views/heng/yw2/ywMoneyList/yuShouDetailModal.vue';

const emit = defineEmits(['success', 'register']);
const isUpdate = ref(true);
const treeData = ref<TreeItem[]>([]);
const { createMessage } = useMessage();
const mouldMainId = ref("");

const formData = ref({})
const totalObj = ref({});
const tableRef = ref<VxeGridInstance>();
const countApproverList = ref([]);
const approverLogViewRef = ref();
const approverLogButtonRef = ref();

const skrq = useModal();
const yushouModal = useModal();

const affrimLogList=ref([]);//抽成记录

const confirmColumns: VxeGridPropTypes.Columns = [
  {
    title: '单据来源编号',
    field: 'orderNo',
    showOverflow: 'title',
    width: 130,
    slots: {
      default: ({ row }) => {
        if (row.type == '销售订单') {
          return row.orderNo;
        }
        let title = "";
        let color = "";
        let props = {
          onClick: () => skrqOpenFn(row)
        };
        if (row.isExclude) {
          title = "该单据存在排除的情况";
          color = "red";
          props.title = title;
          props.style = { color }
        }
        return h('a', props, row.orderNo);
      },
    },
    filters: [{ data: '' }],
    filterRender: {
      name: 'VxeInput',
    },
  },

  {
    title: '收款日期',
    field: 'payTime',
    showOverflow: 'title',
    align: 'center',
    formatter: ({ cellValue, row, column }) => `${cellValue ? util.formatDate(new Date(cellValue)) : ''}`,

    width: 100,
  },
  {
    title: '订单号',
    field: 'piCiHao',
    showOverflow: 'title',
    align: 'center',
    filters: [{ data: '' }],
    filterRender: {
      name: 'VxeInput',
    },
    width: 100,
  },
  {
    title: '发票号',
    field: 'faPiaoHao',
    showOverflow: 'title',
    align: 'center',
    filters: [{ data: '' }],
    filterRender: {
      name: 'VxeInput',
    },
    width: 100,
  },
  {
    title: '类型',
    field: 'type',
    showOverflow: 'title',
    align: 'center',
    width: 100,
  },
  {
    title: '客户编号',
    field: 'customerNo',
    showOverflow: 'title',
    align: 'center',
    width: 80,
    filters: [{ data: '' }],
    filterRender: {
      name: 'VxeInput',
    },
  },
  {
    title: '抽成比例',
    field: 'orderCommissionRate',
    formatter: ({ cellValue, row, column }) => `${cellValue ? cellValue + '%' : ''}`,
    showOverflow: 'title',
    width: 100,
  },
  {
    title: '人民币总金额',
    field: 'totalAllPrice',
    slots: {
      default: ({ row }) => {
        let title = "";
        let color = "";
        let props = {
        };
        if (row.isExclude) {
          title = "该单据存在排除的情况";
          color = "red";
          props.title = title;
          props.style = { color }
        }
        return h('span', props, row.totalAllPrice);
      },
      footer: 'footer_totalAllPrice',
    },
    align: 'center',
    width: 100,
  },
  {
    title: '抽成金额',
    field: 'orderCommissionPrice',
    formatter: ({ cellValue, row, column }) => `${cellValue ? cellValue + '元' : ''}`,
    slots: {
      footer: 'footer_orderCommissionPrice',
    },
    showOverflow: 'title',
    width: 100,
  },
  {
    title: '部门',
    field: 'salesmanDeptName',
    align: 'center',
    width: 80,
  },
  {
    title: '接单人',
    field: 'receiverUserName',
    align: 'center',
    width: 100,
  },
  {
    title: '接单人抽成金额',
    field: 'receiverUserPrice',
    // formatter: ({ cellValue, row, column }) => `${cellValue ? cellValue + '元' : ''}`,
    slots: {
      footer: 'footer_receiverUserPrice',
    },
    align: 'center',
    width: 100,
  },

  {
    title: '跟单人',
    field: 'merchandiserUserName',
    align: 'center',
    width: 100,
  },
  {
    title: '跟单人抽成金额',
    field: 'merchandiserUserPrice',
    // formatter: ({ cellValue, row, column }) => `${cellValue ? cellValue + '元' : ''}`,
    slots: {
      footer: 'footer_merchandiserUserPrice',
    },
    align: 'center',
    width: 100,
  },
  {
    title: '介绍人',
    field: 'introduceUserName',
    align: 'center',
    width: 60,
  },
  {
    title: '介绍人抽成',
    field: 'introduceUserPrice',
    align: 'center',
    width: 60,
    // formatter: ({ cellValue, row, column }) => `${cellValue ? cellValue + '元' : ''}`,
  },
  {
    title: '业务经理',
    field: 'manageUserName',
    align: 'center',
    width: 70,
  },
  {
    title: '经理抽成',
    field: 'manageUserPrice',
    // formatter: ({ cellValue, row, column }) => `${cellValue ? cellValue + '元' : ''}`,
    slots: {
      footer: 'footer_manageUserPrice',
    },
    align: 'center',
    width: 90,
  },
  {
    title: '项目组',
    field: 'xiangMuGroupName',
    align: 'center',
    width: 70,
  },
  {
    title: '项目组抽成',
    field: 'xiangMuGroupPrice',
    // formatter: ({ cellValue, row, column }) => `${cellValue ? cellValue + '元' : ''}`,
    slots: {
      footer: 'footer_xiangMuGroupPrice',
    },
    align: 'center',
    width: 90,
  },
  {
    title: '团建基金',
    field: 'jiJingName',
    width: 100,
  },
  {
    title: '团建金额',
    field: 'jiJingPrice',
    width: 100,
    slots: {
      footer: "footer_jiJingPrice"
    }
  },
];


const gridOptions = reactive<BasicTableProps>({
  // keepSource: true,
  border: true,
  showOverflow: true,
  size: 'mini',
  height: 'auto', // 'auto'
  columns: confirmColumns,
  filterConfig: {
    // remote: true,
  },
  exportConfig: {},

  showFooter: true,
  footerData: [
    { orderNo: '合计' }
  ],
  toolbarConfig: {
    slots: {
      buttons: 'toolbar_buttons',
    },
    refresh: true,
  },

  pagerConfig: {
    enabled: false
  },

});


const dataList = ref({});
const approveNo = ref("");
const approvalLogId = ref("");
const headList = ref([]);
const headTitles = ref([]);


const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
  //打开弹层后的回调
  // resetFields();
  // console.log("--dataList.value:",dataList.value)
  approveNo.value = data.record.approveNo;
  approvalLogId.value = data.record.approvalLogId;

  ywApprovalDetailFn();


});

const getTitle = computed(() => ('业务抽成明细'));

function moneyAffrimLogListFn() {
  let r_data = { approveNo: approveNo.value }
  moneyAffrimLogList(r_data).then(res => {
    if (res.code == 200) {
      affrimLogList.value=res.data;
      tableRef.value?.reloadData(res.data);
      totalObj.value = checkboxCountFn2(res.data);
      gridOptions.footerData = [{ orderNo: "合计:" + res.data.length + "条" }];

    }
  })
}


function countApproverNoTotalFn() {
  let r_data = { approveNo: approveNo.value }

  countApproverNoTotal(r_data).then(res => {
    if (res.code == 200) {
      countApproverList.value = res.data
    }
  })
}

//async function handleSubmit()

const handleSubmit = () => {
  try {

    // const values = await validate();



  } catch (e) {
    console.log(e)
  } finally {
    setDrawerProps({ confirmLoading: false });

  }
}

function sunccFn(result) {
  if (result && result.code == 200) {
    createMessage.success(result.message);
  } else {
    createMessage.error(result.message);
  }
  closeDrawer()
  emit('success');
}

function getUserName(item) {
  let userName = item.userName;
  if (!item.userName) {
    if (item.userType == "manage_user") {
      let deptName = dataList.value.deptName;
      if (deptName) {
        if (deptName == "迪卡侬营销部" || deptName == "OEM营销部") {
          userName = "经理(空)"
        }
      }
    }
  }
  return userName;
}

function skrqOpenFn(record) {
  if (record.type == "收款确认") {
    let t_data = util.copy(toRaw(record));

    if (t_data.orderNo.indexOf("已撤销") != -1 || t_data.orderNo.indexOf("已驳回") != -1 || t_data.orderNo.indexOf("已否决") != -1) {
      t_data.orderNo = t_data.orderNo.replace("已撤销", "").replace("已驳回", "").replace("已否决", "");
    }
    skrq[1].openModal(true, {
      isView: true,
      record: t_data,
    });
  } else {
    let t_data = util.copy(toRaw(record));

    if (t_data.orderNo.indexOf("已撤销") != -1 || t_data.orderNo.indexOf("已驳回") != -1 || t_data.orderNo.indexOf("已否决") != -1) {
      t_data.orderNo = t_data.orderNo.replace("已撤销", "").replace("已驳回", "").replace("已否决", "");
    }
    yushouModal[1].openModal(true, {
      isView: true,
      record: t_data,
    });
  }

}

function openAllFaPiaoFn() {
  skrq[1].openModal(true, {
    isView: true,
    isAll: true,
    record: {
      approveNo: approveNo.value
    },
  });
}





function reloadFn() {

  // approverLogViewRef.value.reloadFn();
  emit('success');
  ywApprovalDetailFn();

  // tableRef.value.commitProxy('reload');

}

async function ywApprovalDetailFn() {
  setDrawerProps({ confirmLoading: true });
  let res: BasicDataResult<any> = {};
  if (approvalLogId.value) {
    res = await ywApprovalDetail({ approvalLogId: approvalLogId.value });
  } else {
    res = await ywApprovalDetailByApproveNo({ approveNo: approveNo.value });
  }

  if (res.code == 200) {
    if (res.data) {
      dataList.value = res.data;
      statusObj.value = paseTags2(res.data);

      approveNo.value = res.data.approveNo;

      //是否需要查询明细项
      if (res.data.fileDataJson) {
        let list = JSON.parse(res.data.fileDataJson);
        let allArr = [];
        for (let i in list) {
          let item = list[i];
          if (item.header.length > 0) {
            let sheetName = item.meta.sheetName;
            let results = item.results;

            if (sheetName == "总表") {
              headTitles.value = item.header;
              headList.value = results;
            } else {
              results.forEach(item => {
                item.姓名 = sheetName;
                allArr.push(item);
              })
            }
          }
        }
        tableRef.value?.reloadColumn(k3Columns);
        tableRef.value?.reloadData(allArr);
      } else {
        tableRef.value?.reloadColumn(confirmColumns);
        moneyAffrimLogListFn();
      }

      countApproverNoTotalFn();
      approverLogViewRef.value.reloadFn();
      approverLogButtonRef.value.reloadFn();

    }
  }
  setDrawerProps({ confirmLoading: false });
}

function cancelFn() {
  closeDrawer();
  emit("success");
  //  tableRef.value.clearValidate();
}



</script>
<style lang="less">
.item-row {
  margin: 0 auto;

  //padding-left: 5%;
  .ant-form-item-label {
    flex: 0 0 28.5%;
    max-width: 28.5%;
  }
}

.count-i {
  width: 200px;
  margin-top: 8px;
}

.count-i-p {
  color: #c65206;
}
</style>
